import React, { useEffect, useState } from "react";
import {
  Button, message, Input, Col, Row, Form, Collapse,
  Slider, InputNumber, Radio
} from "antd";
import { connect } from "react-redux";
import { SETCHOOSEDIRINITSTATE, SETFILEINITSTATE, SETCHOOSEDIR, SETOUTPUTDIR, SETDEALSHOW, SETINNTDEALRESULT } from "@/store/types";
import "./index.less";
import { ipcRenderer } from "electron";
import { isChildPath } from "@/utils"
import { Dispatch, FileInfo, DirState, FileState, StoreState, CurrentFileList, DealResult } from "@/types";
import { ImgCard, CompressImgCard } from "@/components"
const { Panel } = Collapse;

interface IndexProps extends DirState, FileState {
  initFileState: () => void
  initDirState: () => void
  setDealShow: (isshow: boolean) => void
  initDealResult: () => void
}

const FormLayout = {
  labelCol: { lg: 3, md: 4, sm: 24 },
  wrapperCol: { md: 20, lg: 21, sm: 24 }
}

function Index(props: IndexProps) {
  const { chooseDir, isopen, loadding, list, initFileState, initDirState, outputDir } = props
  const [fileList, setList] = useState<CurrentFileList>([])
  const [checkedNum, setCheckedNum] = useState<number>(0) // 选中文件数量
  const [quality, setQuality] = useState<number>(8) // 压缩质量
  const [fileLayout, setLayout] = useState<boolean>(true)
  const [dealResult, setDealRes] = useState<DealResult | null>(null)
  // 如果清除文件夹 选择 就 删除掉文件记录
  useEffect(() => {
    if (!chooseDir) {
      init()
    }
  }, [chooseDir]);
  // list变更 的时候 默认全中
  useEffect(() => {
    checkAllFile(list)
  }, [list])
  useEffect(() => {
    ipcRenderer.on("compressResult", (e, result) => {
      setDealRes(result)
    })
  }, [])

  // 打开 文件夹窗口
  const opendir = (setType: string, stateKey: string) => {
    if (!isopen) {
      ipcRenderer.send("openDialog", ["openDirectory"], setType, stateKey);
    } else {
      message.error("选择文件窗口已打开！");
    }
  };
  //  检测文件夹 图片信息
  const findFile = () => {
    if (list.length) {
      return
    }
    ipcRenderer.send("findDirImg", chooseDir);
  };

  // 选中所有图片
  const checkAllFile = (list: FileInfo[]) => {
    const fileList: CurrentFileList = list.map(item => ({ ...item, checked: true }))
    setCheckedNum(list.length)
    setList(fileList)
  }
  // 修改文件选中状态
  const changeFileCheckStatu = (path: string, checked: boolean) => {
    let newList = fileList.map(i => {
      if (i.path === path) {
        i.checked = !checked
      }
      return i
    })
    let checkedNum = newList.reduce((a, c) => {
      if (c.checked) {
        return a + 1
      }
      return a
    }, 0)
    setCheckedNum(checkedNum)
    setList(newList)
  }
  // 初始化
  const init = () => {
    initFileState()
    initDirState()
    setDealRes(null)
    props.initDealResult()
  }
  // 交给主进程解压
  const start = () => {
    if (!outputDir) {
      return message.error("请选择压缩结果文件夹！")
    } else if (outputDir === chooseDir) {
      return message.error("目标文件夹与结果文件夹不能相同！")
    } else if (isChildPath(chooseDir, outputDir) || isChildPath(outputDir, chooseDir)) {
      return message.warn("建议结果文件夹与目标文件夹为两个单独分开的文件夹!")
    }
    const list = fileList.filter(i => i.checked)
    ipcRenderer.send("compressList", list, { position: outputDir, quality, isRelative: fileLayout })
    props.setDealShow(true)
  }
  return (
    <div className="index-container">
      <Form  {...FormLayout} labelAlign="left"  >
        <Form.Item label="目标文件夹">
          <Input
            readOnly
            type="primary"
            onClick={() => opendir(SETCHOOSEDIR, "chooseDir")}
            value={chooseDir}
            placeholder="请选择需要压缩图片的文件夹"
            prefix={<i className="iconfont icon-folder" />}
          />
        </Form.Item>
        <Form.Item label="结果文件夹">
          <Input type="text"
            onClick={() => opendir(SETOUTPUTDIR, "outputDir")}
            value={outputDir} prefix={<i className="iconfont icon-folder" />}
            readOnly
            placeholder="请选择图片压缩后放入的文件夹"
          />
        </Form.Item>
        <Form.Item label="压缩质量">
          <Row>
            <Col lg={19} md={17} xs={14}>
              <Slider value={quality} onChange={setQuality} min={1} max={9} />
            </Col>
            <Col lg={4} md={6} xs={9} offset={1}>
              <InputNumber addonBefore="质量级别" readOnly value={quality} step={1} min={1} max={9} />
            </Col>
          </Row>
        </Form.Item>
        <Form.Item label="压缩布局">
          <Radio.Group value={fileLayout} onChange={(e) => setLayout(e.target.value)}>
            <Radio value={true}>按照原文件夹布局</Radio>
            <Radio value={false}>统一放在一个文件夹下</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="操作按钮">
          <div className="btns">
            <Button
              loading={loadding}
              disabled={(!chooseDir && !Boolean(list.length)) || (chooseDir && Boolean(list.length))}
              onClick={findFile}
              type="primary"
            >
              检索文件
            </Button>
            <Button onClick={init}>重置状态</Button>
            <Button danger disabled={checkedNum === 0 || Boolean(dealResult)} onClick={start} type="primary">开始解压</Button>
          </div>
        </Form.Item>
      </Form>
      {
        (fileList.length > 0) && <Collapse accordion className="mt10">
          {
            !dealResult && <Panel header={'检测到图片文件' + fileList.length + '张，已选中' + checkedNum + '张'} key="img">
              <Row className="img-wrapper" gutter={16}>
                {fileList.map((item) => (
                  <Col span={6} key={item.path}>
                    <ImgCard onClick={changeFileCheckStatu} fileInfo={item} />
                  </Col>
                ))}
              </Row>
            </Panel>
          }
          {
            dealResult && <>
              <Panel header={"压缩成功：" + dealResult.success + "张"} key="success">
                <Row className="img-wrapper" gutter={16}>
                  {dealResult.successList.map((item) => (
                    <Col span={6} key={item.path}>
                      <CompressImgCard fileInfo={item} />
                    </Col>
                  ))}
                </Row>
              </Panel>
              <Panel header={"压缩失败：" + dealResult.fail + "张"} key="fail">
                {
                  <Row className="img-wrapper" gutter={16}>
                    {dealResult.failList.length ?
                      dealResult.failList.map(item => <Col span={6} key={item.path}>
                        <ImgCard fileInfo={item} />
                      </Col>)
                      : "暂未发现压缩失败图片"
                    }
                  </Row>
                }
              </Panel>
            </>
          }
        </Collapse>
      }
    </div>
  );
}

export const route = {
  path: "/",
};

const mapStateToProps = (state: StoreState) => ({
  ...state.dir,
  ...state.file,
});
const mapDispatchToProps = (dispatch: Dispatch) => ({
  initFileState: () => dispatch({ type: SETFILEINITSTATE }),
  initDirState: () => dispatch({ type: SETCHOOSEDIRINITSTATE }),
  setDealShow: (isShow: boolean) => dispatch({ type: SETDEALSHOW, isShow }),
  initDealResult: () => dispatch({ type: SETINNTDEALRESULT, result: null })
});
export default connect(mapStateToProps, mapDispatchToProps)(Index);
